package com.chixigua.chaos.config.security.auth;

import com.aliyun.oss.HttpMethod;
import com.chixigua.chaos.mapper.MyUserDetailsMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Component("rabcService")
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private MyUserDetailsMapper myUserDetailsMapper;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //加载基础用户信息
        MyUserDetails myUserDetails = myUserDetailsMapper.findByUserName(username);

        //加载用户角色列表
        List<String> roleCodes = myUserDetailsMapper.findRoleByUserName(username);


        //通过用户角色列表加载用户的资源权限列表
        List<String> authorties = myUserDetailsMapper.findAuthorityByRoleCodes(roleCodes);

        //角色是一个特殊的权限，ROLE_前缀
        roleCodes = roleCodes.stream()
                .map(rc -> "ROLE_" +rc)
                .collect(Collectors.toList());

        authorties.addAll(roleCodes);

        myUserDetails.setAuthorities(
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        String.join(",",authorties)
                )
        );


        return myUserDetails;
    }

    public boolean hasPermission(HttpServletRequest request, Authentication authentication){

        Object principal = authentication.getPrincipal();
        boolean a=principal instanceof UserDetails;
        if(principal instanceof UserDetails){

            String username = ((UserDetails)principal).getUsername();
            List<String> urls = myUserDetailsMapper.findUrlsByUserName(username);
            return urls.stream().anyMatch(
                    url -> antPathMatcher.match(url,request.getRequestURI())
            );
        }
        return false;
    }
}
